package com.ruoyi.web.controller.admin.auth;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import com.ruoyi.admin.service.ISystemUserLoginService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AdminUserDO;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StpSystemUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.newSystem.bean.input.AuthLoginReqVO;
import com.ruoyi.newSystem.service.AdminUserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping()
@RequiredArgsConstructor
@Slf4j
public class LoginController {


    private final AdminUserService userService;

    private final ISystemUserLoginService systemUserLoginService;

    private final AdminUserService adminUserService;

    /**
     * 登录
     *
     * @param reqVO 用户信息
     * @return 登录状态
     */
    @PostMapping("/login")
    @SaIgnore
    public AjaxResult login(@RequestBody AuthLoginReqVO reqVO, HttpServletRequest httpServletRequest) throws Exception {
        String s = Md5Utils.hash(reqVO.getPassword());
        AdminUserDO adminUserDO = userService.getUserByUsername(reqVO.getUsername());
        //如果用户不存在就创建用户
        if (adminUserDO == null) {
            //创建用户
            adminUserDO = new AdminUserDO();
            adminUserDO.setPassword(s);
            adminUserDO.setUsername(reqVO.getUsername());
            adminUserDO.setNickname(reqVO.getUsername());
            //密码使用时间
            adminUserDO.setPasswordTime(DateUtils.getTime());
            adminUserDO = adminUserService.createUser(adminUserDO);
        } else {
            //如果用户存在判断密码是否正确
            if (!adminUserDO.getPassword().equals(s)) {
                return AjaxResult.error(500, "账号或密码错误");
            }
        }


        // 登录
        StpSystemUtil.login(adminUserDO.getId());
        //将用户所有的信息都存入satoken 的session 缓存中
        userService.getAllPermissionsSetCache(adminUserDO.getId());
        SaTokenInfo saTokenInfo = StpSystemUtil.getTokenInfo();
        saTokenInfo.setLoginType(String.valueOf(adminUserDO.getUserType()));
        systemUserLoginService.inertLogin(reqVO.getUsername(), saTokenInfo.getTokenValue(), httpServletRequest, adminUserDO.getUserCode());
        return AjaxResult.success("登录成功", saTokenInfo.getTokenValue());
    }


    /**
     * 判断该用户是否第一次登录或者超过30天没有修改过密码
     *
     * @return ajax
     */
    @GetMapping("/isResetPassword")
    public AjaxResult isResetPassword() {
        return userService.isPasswordUpdate();
    }


}


